//
//  YLVerificationCodeViewModel.m
//  YLFinanceService
//
//  Created by she1323 on 2017/8/18.
//  Copyright © 2017年 she1323. All rights reserved.
//

#import "YLVerificationCodeViewModel.h"
#import "NSString+Regex.h"
#import "WHProgressHUD.h"
#import "WHNetworkTool.h"
@interface YLVerificationCodeViewModel ()
@property (nonatomic, strong) dispatch_source_t disTimer;
@end


@implementation YLVerificationCodeViewModel


- (instancetype)init
{
    if (self = [super init]) {
    }
    return self;
}

- (RACCommand *)verificationCommand
{
    if (!_verificationCommand) {
        __weak typeof(self) weakSelf = self;
        _verificationCommand = [[RACCommand alloc] initWithSignalBlock:^RACSignal * _Nonnull(id  _Nullable input) {
            return [RACSignal createSignal:^RACDisposable * _Nullable(id<RACSubscriber>  _Nonnull subscriber) {
                
                
                // 如果有倒计时，结束
                if (_disTimer) {
                    dispatch_source_cancel(_disTimer);
                }
                
                if (![input isValidPhoneNumber]) {
                    [WHProgressHUD showError:@"请输入正确的手机号"];
                    [subscriber sendCompleted];
                    return nil;
                }
                
                
                // 获取验证码
                {
                    NSString *url = [NSString stringWithFormat:@"%@%@", YLURL, weakSelf.urlStr];
                    //NSLog(@"路径%@", url);
                    NSMutableDictionary *params = [NSMutableDictionary dictionaryWithCapacity:1];
                    // 手机号
                    params[@"TelCode"] = input;
                    
                    [[WHNetworkTool shareInstance] sendPostWithUrl:url header:nil params:params success:^(id responseObject) {
                        
                        if ([responseObject[@"httpCode"] integerValue] == 200) {
                            
                        }
                        else {
                            if (weakSelf.disTimer) {
                                dispatch_source_cancel(weakSelf.disTimer);
                            }
                            [subscriber sendNext:@"发送验证码"];
                            [subscriber sendCompleted];
                            [WHProgressHUD showError:responseObject[@"message"]];
                        }
                        
                    } fail:^(NSError *error) {
                        
                        if (weakSelf.disTimer) {
                            dispatch_source_cancel(weakSelf.disTimer);
                        }
                        [subscriber sendNext:@"发验证码"];
                        [subscriber sendCompleted];
                        [WHProgressHUD checkNetPlease];
                    }];
                    
                }
                
                // 倒计时
                {
                    __block int timeout = 59;
                    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
                    dispatch_source_t _timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0,queue);
                    weakSelf.disTimer = _timer;
                    dispatch_source_set_timer(_timer,dispatch_walltime(NULL, 0),1.0*NSEC_PER_SEC, 0); //每秒执行
                    dispatch_source_set_event_handler(_timer, ^{
                        if(timeout<=0){ //倒计时结束，关闭
                            dispatch_source_cancel(_timer);
                            dispatch_async(dispatch_get_main_queue(), ^{
                                [subscriber sendNext:@"发验证码"];
                                [subscriber sendCompleted];
                                
                            });
                        }else{
                            int seconds = timeout % 60;
                            NSString *strTime = [NSString stringWithFormat:@"%.2d", seconds];
                            dispatch_async(dispatch_get_main_queue(), ^{
                                [subscriber sendNext:[NSString stringWithFormat:@"%@秒后重新发送",strTime]];
                            });
                            timeout--;
                        }
                    });
                    
                    dispatch_resume(_timer);
                }
                
                
                
                return nil;
            }];
        }];
    }
    return _verificationCommand;
}


- (void)dealloc
{
    if (_disTimer) {
        dispatch_source_cancel(_disTimer);
    }
    
    [[WHNetworkTool shareInstance] cancel];
    
}


@end
